﻿#region Copyright

// // The contents of this file are subject to the Mozilla Public License
// // Version 1.1 (the "License"); you may not use this file except in compliance
// // with the License. You may obtain a copy of the License at
// //   
// // http://www.mozilla.org/MPL/
// //   
// // Software distributed under the License is distributed on an "AS IS"
// // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// // License for the specific language governing rights and limitations under 
// // the License.
// //   
// // The Initial Developer of the Original Code is Robert Smyth.
// // Portions created by Robert Smyth are Copyright (C) 2008-2013.
// //   
// // All Rights Reserved.

#endregion

namespace NoeticTools.NWorkflow
{
    /// <summary>
    ///     Decorator that wraps an activity over a workflow so that the activity's lifecyle is limited to the child workflow's lifecycle.
    /// </summary>
    public class WorkFlowRulesActivityDecorator<T> : WorkflowRules<T>
    {
        private readonly IWorkflow<T> _innerWorkflow;
        private readonly IActivityListener<T> _innerWorkflowListener;
        private readonly IActivity<T> _outerActivity;

        public WorkFlowRulesActivityDecorator(IActivity<T> outerActivity, IWorkflow<T> innerWorkflow, IActivityListener<T> innerWorkflowListener) : base("")
        {
            _outerActivity = outerActivity;
            _innerWorkflow = innerWorkflow;
            _innerWorkflowListener = innerWorkflowListener;
        }

        protected override void BuildWorkflow()
        {
            base.BuildWorkflow();

            OnBegin
                .Start(_outerActivity).Then
                .EnterStep("_Run");

            using (var x = AddStep<T>("_Run"))
            {
                x.OnEntry.Start(new ActivityListenerSpy<T>(_innerWorkflow, _innerWorkflowListener));
                x.ExitWithAnyResult<T>();
            }
        }
    }
}